<?php
namespace Home\Tool;
abstract  class ACarTool {
    /**
    *
    *  @param  $goods_id int ࠟߝid
    *  @param  $goods_name String ࠟߝݷ
    *  @param  $shop_price float հ໒
    *  @return boolean
    */
    abstract  public  function  add ($goods_id,$goods_name ,$shop_price );
    /**
    *
    *  @param  $goods_id int ࠟߝid
    */
    abstract  public  function  decr($goods_id);
    /**
    *  @param  $goods_id  ࠟߝid
    */
    abstract  public  function  del ($goods_id);
    /**
    *  @return Array
    */
    abstract  public  function  items();
    /**
    *  @return int
    */
    abstract  public  function  calcType ();
    /**
    *  @return int
    */
    abstract  public  function  calcCnt();
    /**
    *  @return float
    */
    abstract  public  function  calcMoney();
    /**
    *  @return void
    */
    abstract  public  function  clear();
}
class CarTool extends ACarTool{
    public $item = [];
    protected static $ins = null;
    final protected function __construct(){
        if(session('?cart')){
            $this->item = session('cart');
        }
    }

    public static function getIns(){
        if(self::$ins == null){
            self::$ins = new self();
        }
        return self::$ins;
    }

    //添加
     public  function  add ($goods_id,$goods_name ,$shop_price ){
         if($this->item[$goods_id]){
             $this->item[$goods_id]['num'] += 1;
         }else{
             $goods = array('goods_name'=>$goods_name,'shop_price'=>$shop_price,'num'=>1);
             $this->item[$goods_id] = $goods;
         }
     }
     //减少
     public  function  decr($goods_id){
         if(isset($this->item[$goods_id])){
             $this->item[$goods_id]['num'] -= 1;
         }
         if($this->item[$goods_id]['num'] <= 0){
             $this->del($goods_id);
         }
     }
     //删除商品
     public  function  del ($goods_id){
         unset($this->item[$goods_id]);
     }
     //liechusuoyou shangpin
     public  function  items(){
         return $this->item;
     }
     //几种
     public  function  calcType (){
         return count($this->item);
     }
     //个数
     public  function  calcCnt(){
         $cnt = 0;
         foreach ($this->item as $v) {
             $cnt += $v['num'];
         }
         return $cnt;
     }
     //总价
     public  function  calcMoney(){
         $money = 0;
         foreach ($this->item as $key => $value) {
             $money += ($value['num'] * $value['shop_price']);
         }
         return $money;
     }
     //清空
     public  function  clear(){
         $this->item = [];
     }
     public function __destruct(){
         session('cart',$this->item);
     }
}
